//
//  OffersViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 8/22/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "OffersViewController.h"
#import "JGoAPI.h"
#import "AppDelegate.h"
#import "User.h"
#import "OffersDetailiewController.h"

@implementation OffersViewController

@synthesize mode = _mode;
@synthesize myCell,segment,dataArr;
@synthesize delegate = _delegate;

-(void)getOfferWithCat:(MBProgressHUD*)progress 
{
    NSDictionary *result = nil;
    NSError *error = nil;
    
    NSString *uid = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSString *lat = [JGoUtility sharedLatitude];
    NSString *lon = [JGoUtility sharedLongitude];
    NSString *cat_id = [NSString stringWithFormat:@"%d",self.segment.selectedSegmentIndex];
    result = [JGoAPI getOffersWithUserId:uid lat:lat lon:lon category:cat_id error:&error];
    
    if ([[result objectForKey:@"data"] isKindOfClass:[NSArray class]] && ![[result objectForKey:@"data"] isKindOfClass:[NSNull class]]) {
        for (NSDictionary *obj in [result objectForKey:@"data"]) {
            [dataArr addObject:obj];
        }

        
    }
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    else {
        NSLog(@"%@",result);
        
        //[JGoUtility showAlert:@"Sucessfully"];                
    }
    
    [progress hide:YES];
    [self.tableView reloadData];
}

- (IBAction)segmentSwitch:(id)sender {
    
    
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Waiting..." 
                          selector:@selector(getOfferWithCat:)];
}
-(void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    dataArr = [[NSMutableArray alloc]init];
    [self.navigationItem setHidesBackButton:NO];
    
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    
    [self setTitle:@"Offers"];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]];
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Waiting..." 
                          selector:@selector(getOfferWithCat:)];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)dealloc
{
    [dataArr release];
    [segment release];
    [myCell release];
    [super dealloc];
}

#pragma mark Table Delegete
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [dataArr count];;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;//([dataArr count] ?  1 + [dataArr count] : 0);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 40;
    }
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
    if (section == 0) {
        UILabel *lblText = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 40)];
        lblText.text = @"   Nearby";
        lblText.font = [UIFont systemFontOfSize:14];
        lblText.backgroundColor = [UIColor clearColor];
        lblText.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];

        [lblText sizeToFit];
        return [lblText autorelease];
    }
    return nil;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell;
    static NSString *OfferCellIdentifier = @"OfferCell";
    cell = [tableView dequeueReusableCellWithIdentifier:OfferCellIdentifier];
    if (cell == nil) {
        cell  = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:OfferCellIdentifier] autorelease];
        [[NSBundle mainBundle] loadNibNamed:@"OffersCell" owner:self options:nil];
        cell = myCell;
        self.myCell = nil;
    }
    
    UILabel *lblTopLine = (UILabel *)[cell viewWithTag:1];
    lblTopLine.textColor = [UIColor colorWithRed:0. green:0.678 blue:0.941 alpha:1];
    UILabel *lblBottomLine = (UILabel *)[cell viewWithTag:2];
    lblBottomLine.textColor = [UIColor colorWithRed:0. green:0.678 blue:0.941 alpha:1];

    UILabel *lblRight = (UILabel *)[cell viewWithTag:3];
    lblRight.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];

    NSDictionary *obj = [dataArr objectAtIndex:indexPath.section];
    NSString *topLineText = [NSString stringWithFormat:@"%@ of %@ @",[obj valueForKey:@"discount"],[obj valueForKey:@"title"]]; 
    lblTopLine.text = topLineText;
    
    NSString *bottomLineText = [NSString stringWithFormat:@"%@",[obj valueForKey:@"shop_name"]];
    lblBottomLine.text = bottomLineText;
    
    lblRight.text = [JGoUtility distanceString:[[obj valueForKey:@"distance"] stringValue]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *aOffer = [self.dataArr objectAtIndex:indexPath.section];
    
    if (self.mode == OfferForNormal) {
        OffersDetailiewController *oVC = [[OffersDetailiewController alloc]initWithNibName:@"OffersDetailiewController" bundle:nil];
        oVC.data = aOffer;
        [self.navigationController pushViewController:oVC animated:YES];
        [oVC release];
    }
    else {
        
        if ([_delegate respondsToSelector:@selector(offersViewController:didSelectedWithOffer:)]) {
            [_delegate offersViewController:self didSelectedWithOffer:aOffer];
        }
    }     
}

@end
